package Classic150;

public class 环形子数组的最大和 {
    /*
        最大和只会分两种情况，一是在数组中间，二是数组首尾，第二种可以通过数组和减去首尾中间的最小和得到，故计算非环形的最大和和最小和求解
     */
    public int maxSubarraySumCircular(int[] nums) {
        int maxSum = Integer.MIN_VALUE, minSum = Integer.MAX_VALUE;
        int sum = 0, sum1 = 0, sum2 = 0;
        for (int num : nums) {
            sum += num;
            sum1 = Math.max(sum1 + num, num);
            maxSum = Math.max(maxSum, sum1);
            sum2 = Math.min(sum2 + num, num);
            minSum = Math.min(minSum, sum2);
        }
        if (sum == minSum) return maxSum;
        return Math.max(maxSum, sum - minSum);
    }
}
